var DocData={
    cardId:baseFn.getQueryString('cardId',true),
    cardType:baseFn.getQueryString('cardType',true),
    editing:false,
    // seled:[],//多选
    // tempseledId:[],//多选
    seledService:[],
    tempSelServiceId:'',
    popService:function(data){
        var that= this
        var _updata = {
            state:1
        }
        if(service == ''){
            service = baseFn.rpDataTables('.js_service_list',{
                dom:'<"zcdatatabletop clearfix"f>rt<"bottom"ip<"clear">>',
                ajUrl:baseUrl.base+baseUrl.init+'selectInitServiceList',
                ajDataSrc:"results",
                ajData:_updata,
                ajType:'get',
                scrollY:'50%',
                select:'multi',
                autoWidth:false,
                columns:[
                    { "data": "serviceName",width:"25%",defaultContent:'',className:'imgpwrap img1p',render:function(data,type,row, meta){
                        var _img=baseUrl.tempHeadImg
                        if(baseFn.notNull(row.serviceImg)){
                            _img = row.serviceImg
                        }
                        return '<div class="datatable_img_div" data-vals="'+_img+'" style="background-image:url('+_img+')"></div>\
                                                <div class="bespeak_change_name">\
                                                    <span>'+data+'</span>\
                                                </div>'
                    }},
                    { "data": "serviceCost",width:"15%",defaultContent:''},
                    { "data": "createTime",width:"30%",defaultContent:'',render:function(data,type,row, meta){
                        return baseFn.timestampToTime(data)
                    }},
                    { "data": 'serviceId',defaultContent:'无',width:"20%",render:function(data,type,row, meta){
                        /*if(DocData.tempseledId.some(function(val){
                            return val == data
                        }) || row.seled == 1){ //多选*/
                        if(DocData.tempSelServiceId == data || row.seled == 1){   
                            return '<a href="javascript:void(0)" class="datatablebtn datatablebtnRed canceled" data-vals="'+row.serviceId+'">取消</a>'
                        }else{
                            // row.seled = 0 //多选
                            return '<a href="javascript:void(0)" class="datatablebtn seled" data-vals="'+row.serviceId+'">选择</a>'
                        }
                        
                        
                    }}
                ],
                initComplete:function(){
                },
                drawCallback: function( settings ) {
                    $('.zcdatatabletop .dataTables_filter input').attr('placeholder','请输入名称')
                    $('.seled').off('click').on('click',function(){
                        var _id = $(this).data('vals')
                        var _tr = $(this).parents('tr')
                        if(baseFn.notNull(DocData.tempSelServiceId)){
                            var _oldTr = $('.canceled[data-vals='+DocData.tempSelServiceId+']').parents('tr')
                            var _oldD = service.row(_oldTr).data()
                            DocData.tempSelServiceId=''
                            _oldD.seled = 0
                            service.row(_oldTr).data(_oldD).draw(false) 
                        } 
                        DocData.tempSelServiceId = _id
                        var _d = service.row(_tr).data()
                        _d.seled=1
                        service.row(_tr).data(_d).draw(false)                        
                    })
                    $('.canceled').off('click').on('click',function(){
                        var _id = $(this).data('vals')
                        var _tr = $(this).parents('tr')
                        DocData.tempSelServiceId = '';                        
                        var _d = service.row(_tr).data()
                        _d.seled=0
                        /*
                        DocData.tempseledId = DocData.tempseledId.filter(function(val){
                            return val != _d.serviceId
                        })
                        */
                        service.row(_tr).data(_d).draw(false)
                        
                    })
                    //图片初始化
                    $('.datatable_img_div').each(function(ids,val){
                        baseFn.imgSize({
                            src: $(val).data('vals'),
                            hFn: function(res) {
                                res.dom.css({'background-size':'auto 100%'})           
                            },
                            wFn: function(res) {
                                res.dom.css({'background-size':'100% auto'}) 
                            },
                            ratio: 1,
                            otherData: {
                                dom:$(val)
                            }
                        })
                    })
                }
            })
        }else{
            service.ajax.reload()
        }
    },
    renderSelList:function(data){
        var that=this
        var _data = data || that.seledService;
        var _txt='';
        if(_data.length == 0){
            $('.js_list_wrap').addClass('hidden')
            $('.js_list_wrap .service_list').html('')
        }else{
            $('.js_list_wrap').removeClass('hidden')
            _txt += '<div class="rows listelm">\
                        <div class="cols8">服务名称</div>\
                        <div class="cols10">次数</div>';
            if(!DocData.editing){
                _txt +='<div class="cols2">操作</div>';
            }
            _txt +='</div>';
            for(var h1=0;h1<_data.length;h1++){
                _txt += '<div class="rows listelm zcformelm" data-vals="'+_data[h1].serviceId+'">\
                            <div class="cols8"><p class="zcform_text">'+_data[h1].serviceName+'</p></div>\
                            <div class="cols10 "><input class="js_cardCount zcform_input" style="width:2rem;margin-right:2px" name="cardCount" value="'+(_data[h1].cardCount || 1)+'" />次</div>';
                if(!DocData.editing){
                    _txt += '<div class="cols2" style=""><p class="zcform_text"><a href="javascript:void(0)" class="font_blue remove">删除</a></p></div>';
                }else{
                    _txt += '<div class="cols2" style=""><p class="zcform_text"><a href="javascript:void(0)" class="">--</a></p></div>';
                }
                _txt += '</div>';
            }
            $('.js_list_wrap .service_list').html(_txt)
            $('.remove').off('click').on('click',function(){
                var _parent = $(this).parents('.listelm')
                var _id = _parent.data('vals');
                /*
                that.seled = that.seled.filter(function(val){
                    return val.serviceId != _id
                })
                */
                that.tempSelServiceId = ''
                that.seledService = []
                that.renderSelList()
                
            })
            $('input[name=cardCount]').off('change').on('change',function(){
                if(!baseFn.notNull($(this).val()) || !Boolean(Number($(this).val()))){
                    $(this).val(0)
                }
                var _parent = $(this).parents('.listelm')
                var _id = _parent.data('vals');
                for(var h2=0;h2<_data.length;h2++){
                    if(_data[h2].serviceId == _id){
                        _data[h2].cardCount = $(this).val()
                    }
                }
                // console.log(that.seledService )
            })
        }
        
    },
    initBase:function(data){
        var _data = data || this.baseData;
        $('.js_cardchage .zcform_check1[data-vals='+_data.cardType+']').trigger('click');
        $('input[name=cardName]').val(_data.cardName);
        $('textarea[name=discountDesc]').val(_data.discountDesc).prop('readonly',true);
        $('select[name=subclinicIds]').val(_data.subclinicIds == null?0:_data.subclinicIds).prop("disabled", true);
        $('input[name=validTime]').val(_data.validTime).prop('readonly',true);
        $('input[name=accountDiscount]').val(_data.accountDiscount).prop('readonly',true);
        if(_data.cardType == 1){
            //满减券
            $('input[name=discountCosts]').val(_data.discountCosts).prop('readonly',true);
            $('input[name=targetCost]').val(_data.targetCost).prop('readonly',true);
        }else if(_data.cardType == 3){
            //通用券
            $('input[name=discountCost]').val(_data.discountCosts).prop('readonly',true);
        }else if(_data.cardType == 2){
            //体验券
            $('.js_validTimebtn').prop('disabled',true)
            this.renderSelList([{
                serviceId:_data.serviceId,
                serviceName:_data.serviceName,
                cardCount:_data.cardCount
            }])
        }else if(_data.cardType == 4){
            $('input[name=cardValue]').val(_data.cardValue).prop('readonly',true);
        }else if(_data.cardType == 5){
            this.renderSelList([{
                serviceId:_data.serviceId,
                serviceName:_data.serviceName,
                cardCount:_data.cardCount
            }])
        }
        $('input[name=cardCount]').val(_data.cardCount).prop('readonly',true);
        if(DocData.cardId != ''){
            DocData.editing = true
        }
        
        
    }
}
var service = ''

//卡券列表
var cardDT = baseFn.rpDataTables('.card_list', {
    ajUrl: baseUrl.base + baseUrl.card + 'selectSysAccountCardList',
    ajDataSrc: "results",
    select: true,
    sessionPageKey: "cardPage",
    ajType: 'get',
    autoWidth:false,
    scrollY: windowOffsetData.tableHeight(),
    columns: [
        {
            "data": "cardName",
            defaultContent: '',
            width: '25%',
            className: 'imgpwrap img2p',
            render: function (data, type, row, meta) {
                var _img=baseUrl.tempHeadImg
                if(baseFn.notNull(row.cardImg)){
                    _img = row.cardImg
                }
                return '<div class="datatable_img_div" data-vals="'+_img+'" style="background-image:url('+_img+')"></div>\
                            <div class="pwrap">\
                                <span>' + data + '</span>\
                                <span>售价 ￥' + row.accountDiscount + '</span>\
                            </div>'
            }
        },
        {
            "data": "cardType", defaultContent: '', width: '20%', render: function (data, type, row, meta) {
            // 1满减，2体验券，3优惠，4充值，5记次卡
            if (row.cardType == "4") {
                return "价值" + row.cardValue + "元余额";
            } else {
                return '适用于【' + row.serviceName + '】总次数' + row.cardCount + '次';
            }
        }
        },
        {"data": "useCount", width: '10%', defaultContent: '0'},
        {"data": "createTimeStr", width: '20%', defaultContent: '无'},
        {"data": "cardState", defaultContent: '无', width: '20%', render: function (data, type, row, meta) {
            var _flagStr = "";
            if (row.cardState == 1) {
                _flagStr = "下架";
            } else {
                _flagStr = "上架";
            }
            // return '<a class="datatablebtn remove" data-vals="'+row.cardId+'" onclick="deleteCardInfo(this)">删除</a>\
            return '<button class="datatablebtn datatablebtnRed updata" data-vals="'+row.cardId+'" onclick="updateCardInfo(this)">'+_flagStr+'</button>\
                    <a class="datatablebtn datatablebtnGray edits" href="javascript:void(0)"  data-vals="'+row.cardId+'">编辑</a>'
        }
        }
    ],
    initComplete: function () {},
    page: function () {
        // alert( $.session.get("cardPage"));
    },
    drawCallback: function (settings) {
        $('.edits').off('click').on('click', function () {
            //权限管理 26卡券管理 - 添加/编辑/下架/删除卡项
            if(baseFn.getPower(26)){
                baseFn.infoDialog('您没有权限操作该功能')
                return false
            }
            var _id = $(this).data('vals')
            var _data = cardDT.row($(this).parents('tr')).data()
            baseFn.goPath('gotoAddCard',{cardId:_id,cardType:_data.cardType})
        })
        //图片初始化
        $('.datatable_img_div').each(function(ids,val){
            baseFn.imgSize({
                src: $(val).data('vals'),
                hFn: function(res) {
                      res.dom.css({'background-size':'auto 100%'})           
                },
                wFn: function(res) {
                    res.dom.css({'background-size':'100% auto'}) 
                },
                ratio: 1,
                otherData: {
                    dom:$(val)
                }
            })
        })
    }
})
function deleteCardInfo(view) {
    var _tr = $(view).parents('tr'),_data=cardDT.row(_tr).data()
    baseFn.dialog({
        content:'确定删除该卡项么？',
        ok:function(){
            $.ajax({
                type: "POST",
                url: baseUrl.base + "card/deleteSysAccountCardInfo",
                data: {"cardId": _data.cardId},
                success: function (data) {
                    if (data.code == "0") {
                        baseFn.infoDialog('删除成功')
                        cardDT.row(_tr).remove().draw(true);
                    } else {
                        baseFn.infoDialog(data.info)
                    }
                }
            });
        }
    })
    
}
function updateCardInfo(view) {
    //权限管理 26卡券管理 - 添加/编辑/下架/删除卡项
    if(baseFn.getPower(26)){
        baseFn.infoDialog('您没有权限操作该功能')
        return false
    }
    var _tr = $(view).parents('tr');
    var _data = cardDT.row(_tr).data();
    if(_data.cardState == 0){
        _data.cardState = 1
    }else{
        _data.cardState = 0
    }
    var _upData = {
        cardId:_data.cardId,
        cardState:_data.cardState
    }
    $.ajax({
        type: "POST",
        url: baseUrl.base + "card/updateSysAccountCardInfo",
        data: _upData,
        success: function (data) {
            if (data.code == "0") {
                baseFn.infoDialog('成功')
                cardDT.row(_tr).data(_data).draw(true)
            } else {
                baseFn.infoDialog('失败')
            }
        }
    });
}

//初始化控件设置
var myValidform = $(".js_cardEdit").Validform({
    tiptype:3
});

$('.js_addService').on('click',function(){
    if(DocData.editing){
        return false
    }    
    baseFn.dialog({
        title:'请选择服务',
        content:$('.dialogelm.js_service'),
        width:'50em',
        height:'55vh',
        ok:function(){
            /* 多选
            DocData.seled = service.rows().data().filter(function(val){
                return val.seled == 1
            }).toArray()
            DocData.seled.map(function(val){
                DocData.tempseledId.push(val.serviceId)
            })
            */
           if(DocData.tempSelServiceId != ''){
            DocData.seledService = service.rows().data().filter(function(val){
                return val.serviceId == DocData.tempSelServiceId
            }).toArray()
            for(var i=0;i<DocData.seledService.length;i++){
                DocData.seledService[i].cardCount= 1
            }
            DocData.renderSelList()
           }else{
               baseFn.infoDialog('请选择一项服务！')
               return false;
           }
            // console.log(DocData.tempseledId)
            
        },
        cancel:function(){
            DocData.tempSelServiceId = ''
            /* 多选
            DocData.seled.map(function(val){
                DocData.tempseledId.push(val.serviceId)
            })
            */
        }
    })
    DocData.popService()
    // setTimeout(function(){},5000)
    
})
// 切换
$('.js_cardchage .zcform_check1').on('click',function(){
    if(DocData.editing){
        return false
    }
    $(this).addClass('zcaccheck').siblings('.zcform_check1').removeClass('zcaccheck');
    var _id = $(this).data('vals')
    if(_id == 5){
        $('.js_card1').removeClass('hidden')
        $('.js_card2').addClass('hidden') 
        DocData.seledService=[]
        DocData.tempSelServiceId=''
        DocData.renderSelList()
        myValidform.ignore($('input[name=cardValue]'));
        myValidform.unignore($('input[name=validTime]'));
    }else if(_id == 4){
        $('.js_card2').removeClass('hidden')
        $('.js_card1').addClass('hidden')
        myValidform.unignore($('input[name=cardValue]'));
        myValidform.unignore($('input[name=validTime]'));
    }
})

//编辑
var _upurl='saveSysAccountCardInfo',_txt = '添加成功';
if(baseFn.notNull(DocData.cardId)){
    $('.js_brandLast').text('编辑计次卡')
    if(baseFn.notNull(DocData.cardType) && DocData.cardType == 4){
        $('.js_brandLast').text('编辑储值卡')
    }
    _txt = '编辑成功'
    _upurl = 'updateSysAccountCardInfo'
    
    $.get(baseUrl.base+baseUrl.card+'selectSysAccountCardInfo',{cardId:DocData.cardId},function(res){
        if(res.code == 0){
            DocData.baseData = res.results
            DocData.initBase(res.results)
            DocData.editing = true
            // baseFn.infoDialog(_txt)
        }else{
            baseFn.infoDialog(res.msg)
        }
    },'json')
}else{
    $('.js_cardchage .zcform_check1[data-vals=5]').trigger('click')
}

$('.edit_ok').on('click',function(){
    if($('.js_cardchage').find('.zcaccheck').length ==0){
        baseFn.infoDialog('请选择卡项类别！')
        return false
    }
    
    var _updata={
        cardName:$('input[name=cardName]').val(),
        cardType:$('.js_cardchage').find('.zcaccheck').data('vals')
    }
    if(_updata.cardType == 5){
        //计次卡
        myValidform.ignore($('input[name=cardValue]'));
        myValidform.unignore($('input[name=validTime]'));
    }if(_updata.cardType == 4){
        //计次卡
        myValidform.unignore($('input[name=cardValue]'));
        myValidform.unignore($('input[name=validTime]'));
    }else{
        myValidform.unignore($('input[name=cardValue]'));
        myValidform.ignore($('input[name=validTime]'));
    }
    if(!myValidform.check()){
        return false
    }
    
    if(baseFn.notNull(DocData.cardId)){
        
    }else{
	//myValidform.unignore(selector);
    if(_updata.cardType == 5){
        //计次卡
        if(DocData.seledService.length != 0){
            if(!DocData.seledService[0].cardCount){
                baseFn.infoDialog('请为该服务填写次数！');
                return false;
            }else{
                _updata.serviceId=DocData.seledService[0].serviceId
                _updata.cardCount=DocData.seledService[0].cardCount
                _updata.validTime=$('input[name=validTime]').val()
            }
            
        }else{
            baseFn.infoDialog('请选择一项服务！');
            return false;
        }
        
    }else{
        //储值卡
        _updata.cardValue = $('input[name=cardValue]').val()
        _updata.validTime=$('input[name=validTime]').val()
    }
    }
    if(DocData.cardId != ''){
        _updata.cardId = DocData.cardId;
    }
    _updata.accountDiscount = $('input[name=accountDiscount]').val()
    // console.log(_updata)
    //return false;
    $.post(baseUrl.base+baseUrl.card+_upurl,_updata,function(res){
        if(res.code == 0){
            baseFn.infoDialog(_txt,function(){
                baseFn.goPath('gotoCardManagement')
            })
        }else{
            baseFn.infoDialog(res.msg)
        }
    },'json')
})
$('.edit_cancel').on('click',function(){
    baseFn.goPath('gotoCardManagement')
})
//表格自适应
window.onresize = function(){
    windowOffsetData.refresh();
    $(cardDT.table().body()).parents('.dataTables_scrollBody').css('max-height',windowOffsetData.tableHeight());
    cardDT.draw(false);
}
